import { createElement, useEffect, useState } from 'react';
import { Button, Card, Drawer, message, Popconfirm, Spin, Tooltip, Upload, Image } from 'antd';
import './index.less';
import {
  CopyFilled,
  FunnelPlotFilled,
  UploadOutlined,
  HighlightOutlined,
  FileWordFilled,
  DownloadOutlined,
  EyeOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { Editor } from '@tinymce/tinymce-react';
import { downloadFile, stringToDOM, updateProp } from './utils';

export interface FormContainerSetProps {
  title?: string;
  describe?: string;
  codeType?: string;
  fileList?: any;
  formTheme?: { title?: string; url?: string; mainColor?: string };
  children?: any;
  __designMode?: string;
}

export const FormContainerSet = (props: FormContainerSetProps) => {
  const { children, formTheme, __designMode, title, describe, codeType, fileList } = props;
  // const [mainColor, setMainColor] = useState('');
  // 是否显示富文本
  const [showElement, setShowElement] = useState(false);
  // 附件预览弹窗
  const [open, setOpen] = useState(false);
  // 富文本编辑器内容
  const [content, setContent] = useState(describe);
  // 是否为编辑态
  const isDesign = __designMode === 'design';
  // 预览附件url
  const [previewUrl, setPreviewUrl] = useState('');
  // 预览图片
  const [visible, setVisible] = useState(false);

  // getDominantColor(formTheme.url, (dominantColor) => {
  //   console.log(dominantColor)
  //   setMainColor(dominantColor);
  // });

  const handleEditorChange = (content, editor) => {
    setContent(content);
  };
  // 隐藏富文本
  const confirm = () => {
    setShowElement(false);
  };
  // 显示富文本
  const describeClick = () => {
    setShowElement(true);
  };
  // 物料组件点击
  const handleClick = (e, item) => {
    e.persist();
    const isRich = e.target.closest('.tox-tinymce');
    const isDescribe = e.target.closest('.topHandleDes');
    const handleId = e.target.closest('.handleId');
    if (!isRich) {
      confirm();
    }
    if (!isDescribe && showElement) {
      updateProp('describe', content);
    }
    if (handleId && isDesign) {
      describeClick();
    }
  };
  const [fakeFileList, setFakeFileList] = useState([]);
  // 附件列表变化
  const handleChange = (info) => {
    const isOver = info.fileList.every((item) => {
      return item.status !== 'uploading';
    });
    // 判断是否上传成功
    const newFileList = [...info.fileList];
    setFakeFileList(newFileList);
    if (isOver) {
      updateProp('fileList', newFileList);
    }
  };
  // 下载
  const downLoad = (item) => {
    if (item.response.code === 200) {
      // 遍历获取所点击的文件 暂用name匹配
      item.response.data.forEach((i) => {
        if (i.name === item.name) {
          // 上传成功 进行下载
          downloadFile(i.url, i.name);
        }
      });
    }
  };
  // 附件组件相关属性
  const uploadProps = {
    action: '/api/v1/upload',
    headers: {
      token: localStorage.getItem('user_token'),
    },
    onChange: handleChange,
    multiple: true,
    showUploadList: false,
    fileList: Array.from(new Set([...fileList, ...fakeFileList])),
  };
  // 预览附件
  const previewFile = (item) => {
    setPreviewUrl(item.response.data[0].url);
    if (item.response.data[0].url.includes('.png')) {
      setVisible(true);
    } else {
      setOpen(true);
    }
  };
  // 删除附件
  const deleteFile = (item) => {
    const newList = JSON.parse(JSON.stringify(fileList));
    const index = newList.findIndex((i) => i.uid === item.uid);
    newList.splice(index, 1);
    message.success('删除成功');
    updateProp('fileList', newList);
  };
  useEffect(() => {
    // 将字符串转换为 DOM 元素列表
    const domElements = stringToDOM(describe);
    // 将每个 DOM 元素插入到文档中
    domElements.forEach((node) => document.getElementById('describe').appendChild(node));
  }, []);
  return (
    <div
      className="formTitleContainer"
      style={{ backgroundColor: formTheme.mainColor }}
      onClick={handleClick}
    >
      <div className="top">
        <Card
          // hoverable
          cover={
            formTheme && (
              <img
                alt="example"
                src={
                  formTheme.title === '默认'
                    ? '/lowcode/fields/defaultThemeShow.png'
                    : formTheme.url
                }
              />
            )
          }
        >
          <div>
            {/* 标题 */}
            <div className="title">{title}</div>

            {/* 描述 */}
            {showElement && (
              <Editor
                apiKey="za2phvvh00jmfmvxnyr9qbeh6gwkhgami54dzx596b1zb03u"
                init={{
                  height: 250,
                  language: 'zh_CN',
                  // 隐藏右下角技术支持
                  branding: false,
                  menubar: false,
                  placeholder: '添加应用描述',
                  toolbar:
                    'undo redo | blocks | ' +
                    'bold italic forecolor | alignleft aligncenter ' +
                    'alignright alignjustify | bullist numlist outdent indent | ' +
                    'removeformat | customButton',
                  // setup: (editor) => {
                  //   editor.ui.registry.addButton('customButton', {
                  //     text: '完成',
                  //     onAction: confirm,
                  //   });
                  // },
                  plugins: [
                    'advlist',
                    'autolink',
                    'lists',
                    'link',
                    'image',
                    'charmap',
                    'preview',
                    'anchor',
                    'searchreplace',
                    'visualblocks',
                    'code',
                    'fullscreen',
                    'insertdatetime',
                    'media',
                    'table',
                    'code',
                    'help',
                    'wordcount',
                  ],
                  content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
                }}
                value={content}
                onEditorChange={handleEditorChange} // 内容变化时的事件处理
              />
            )}
            <div className={showElement ? 'hide' : ''}>
              <div
                id="describe"
                className={content ? 'topHandle handleId' : 'topHandle handleId hide'}
              >
                {/* {describe} */}
              </div>
              {isDesign && (
                <div className={content ? 'topHandleDes handleId hide' : 'topHandleDes handleId'}>
                  <CopyFilled className="handleIcon" />
                  添加应用描述
                </div>
              )}
            </div>
            {/* 编号格式 */}
            {isDesign && (
              <div className="topHandle">
                <FunnelPlotFilled className="handleIcon" />
                编号格式
              </div>
            )}
            {/* 添加附件 */}
            {isDesign && (
              <div className="topHandle">
                <Upload {...uploadProps}>
                  <UploadOutlined className="handleIcon" />
                  添加附件
                </Upload>
              </div>
            )}
            {fileList.map((item) => {
              return (
                <Spin spinning={item.status === 'uploading'}>
                  {item.response.code === 200 ? (
                    <div
                      className={item.response.code !== 200 ? 'fileListSelf error' : 'fileListSelf'}
                    >
                      <div className="fileItem">
                        <FileWordFilled className="fileItemIcon" />
                        {/* <Tooltip title={item.name}>
                          <div className="fileName">{item.name}</div>
                        </Tooltip> */}
                        <div className="fileName">{item.name}</div>
                      </div>
                      <div className="fileHandle">
                        <div className="fileHandleContent">
                          {item.response.code === 200 && (
                            <Tooltip title="下载">
                              <DownloadOutlined
                                className="fileHandleIcon"
                                onClick={() => {
                                  downLoad(item);
                                }}
                              />
                            </Tooltip>
                          )}
                          {!isDesign && (
                            <Tooltip title="预览">
                              <EyeOutlined
                                className="fileHandleIcon"
                                onClick={() => {
                                  previewFile(item);
                                }}
                              />
                            </Tooltip>
                          )}
                          {isDesign && (
                            <Popconfirm
                              title="删除附件"
                              onConfirm={() => {
                                deleteFile(item);
                              }}
                              okText="确认"
                              cancelText="取消"
                            >
                              <Tooltip title="删除">
                                <DeleteOutlined className="fileHandleIcon" />
                              </Tooltip>
                            </Popconfirm>
                          )}
                        </div>
                      </div>
                    </div>
                  ) : (
                    isDesign && (
                      <Tooltip title={item.response.message}>
                        <div
                          className={
                            item.response.code !== 200 ? 'fileListSelf error' : 'fileListSelf'
                          }
                        >
                          <div className="fileItem">
                            <FileWordFilled className="fileItemIcon" />
                            {/* <Tooltip title={item.name}>
                                <div className="fileName">{item.name}</div>
                            </Tooltip> */}
                            <div className="fileName">{item.name}</div>
                          </div>
                          <div className="fileHandle">
                            <div className="fileHandleContent">
                              {item.response.code === 200 && (
                                <Tooltip title="下载">
                                  <DownloadOutlined
                                    className="fileHandleIcon"
                                    onClick={() => {
                                      downLoad(item);
                                    }}
                                  />
                                </Tooltip>
                              )}
                              {!isDesign && (
                                <Tooltip title="预览">
                                  <EyeOutlined
                                    className="fileHandleIcon"
                                    onClick={() => {
                                      previewFile(item);
                                    }}
                                  />
                                </Tooltip>
                              )}
                              {isDesign && (
                                <Popconfirm
                                  title="删除附件"
                                  onConfirm={() => {
                                    deleteFile(item);
                                  }}
                                  okText="确认"
                                  cancelText="取消"
                                >
                                  <Tooltip title="删除">
                                    <DeleteOutlined className="fileHandleIcon" />
                                  </Tooltip>
                                </Popconfirm>
                              )}
                            </div>
                          </div>
                        </div>
                      </Tooltip>
                    )
                  )}
                </Spin>
              );
            })}
            {/* 表单样式 */}
            {isDesign && (
              <div className="topHandle">
                <HighlightOutlined className="handleIcon" />
                表单样式
              </div>
            )}
          </div>
        </Card>
      </div>
      <div className="content">{children}</div>
      {/* {!isDesign && (
        <div className="footer">
          <Button type="primary" htmlType="submit" form={children[0].props.id}>
            提交
          </Button>
          <Button htmlType="reset" form={children[0].props.id}>
            重置
          </Button>
        </div>
      )} */}
      <Drawer
        placement={'right'}
        closable={false}
        onClose={() => {
          setOpen(false);
        }}
        destroyOnClose
        visible={open}
        key={'right'}
        width={'65%'}
        forceRender
      >
        <iframe
          id="previewFileMask"
          frameborder="0"
          src={`https://view.officeapps.live.com/op/view.aspx?src=${previewUrl}`}
          style={{ width: '100%', height: '100%' }}
          frameborder="0"
        ></iframe>
      </Drawer>
      <Image
        width={200}
        style={{ display: 'none' }}
        src={previewUrl}
        preview={{
          visible,
          src: previewUrl,
          onVisibleChange: (value) => {
            setVisible(value);
          },
        }}
      />
    </div>
  );
};
